<template>
  <div class="main-container">
    <div class="main-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{path: '/aggregate'}">聚合模块管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增关键词</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="wrap">
      <div class="content">
        <el-form class="mt-30" ref="form" :model="form" label-width="150px" style="width: 800px;">
          <div style="width:450px">
            <el-form-item label="关键词" prop="majorWord" :rules="[ { required: true, message: '关键词不能为空'}]">
              <el-input v-model="form.majorWord"></el-input>
            </el-form-item>
            <el-form-item label="pc封面图片" prop="pcCoverImage">
              <el-upload
                class="avatar-uploader"
                :action="actionUrl + '?fileType=2&businessType=1'"
                :show-file-list="false"
                :on-success="imageSuccess"
                :file-list="imageList"
                >
                <img v-if="form.pcCoverImage" :src="form.pcCoverImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item prop="memo" style="width:700px;color:red">
              <span>* 建议上传图片尺寸：230 * 140（可以倍数增大）<br/>&nbsp;&nbsp;内容放在中间区域，上下左右预留背景，防止鼠标滑过图片放大时边上内容被遮挡</span>              
            </el-form-item>
            <el-form-item label="手机封面图片" prop="wapCoverImage">
              <el-upload
                class="avatar-uploader"
                :action="actionUrl + '?fileType=2&businessType=1'"
                :show-file-list="false"
                :on-success="phoneImageSuccess"
                :file-list="phoneImageList"
                >
                <img v-if="form.wapCoverImage" :src="form.wapCoverImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <span  style="color:red;white-space: nowrap;">* 建议上传图片尺寸：240 * 180（可以倍数增大）</span>
              <br/>&nbsp;&nbsp;<span style="color:red">内容放在中间区域，上下左右预留背景</span>
            </el-form-item>
            <!-- <el-form-item label="上传视频" v-if="form.type == 2 || form.type == 3" prop="advertVideoUrl">
              <el-upload
               
                :action="actionUrl + '?fileType=3&businessType=1'"
                :on-success="videoSuccess"
                :file-list="videoList"
                :limit="1"
                :on-remove="videoHandleRemove"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <span>如需替换文件,先删除</span>
              </el-upload>
            </el-form-item>

            
            <el-form-item label="是否热门" prop="isHot">
              <div class="help-tip el-iconhelp_tip element-icons" style="left: -90px;">
                <p class="help-tip-content">如果选择是，该活动可以在最新活动页面的轮播图中展示。</p>
              </div>
              <el-switch v-model="form.isHot" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item> -->
            <el-form-item label="排序" prop="sort">
              <div class="help-tip el-iconhelp_tip element-icons" style="left: -62px;">
                <p class="help-tip-content">页面中可以通过“排序”进行倒序排序。</p>
              </div>
              <el-input-number v-model="form.sort" :min="0" :controls="false"></el-input-number>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <div class="help-tip el-iconhelp_tip element-icons" style="left: -62px;">
                <p class="help-tip-content">草稿：表示数据刚新增，页面中查询不到此数据。<br/>已发布：表示数据已经发布，页面中可以查到此数据。<br/>下线：表示数据已经下线，页面中查询不到。</p>
              </div>
              <el-select v-model="form.status" style="width: 100%">
                <el-option :value="1" label="草稿"></el-option>
                <el-option :value="2" label="已发布"></el-option>
                <el-option :value="3" label="下线"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="描述" prop="seoDesc">
              <el-input v-model="form.seoDesc" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="关键字" prop="seoKeyword">
              <el-input v-model="form.seoKeyword" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="关键词详情" >
            <!-- <quill-editor 
              ref="myTextEditor"
              v-model="content"
              :options="editorOption"
              @change="onEditorChange($event)"
              style="height:300px">
            </quill-editor> -->
            <el-input
                ref="myTextEditor"
                type="textarea"
                :rows="10"
                style="width:500px;"
                placeholder="请输入关键字详情"
                @change="onEditorChange($event)"
                v-model="content">
              </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
        <el-upload
          :action="actionUrl + '?fileType=2&businessType=4'"
          :on-success="quillSuccess"
          style="display:none"
          >
          <el-button type="primary" id="uploadHidden">点击上传</el-button>
        </el-upload>
      </div>
    </div>
  </div>
</template>

<script>
  import {quillEditor} from 'vue-quill-editor'
  import 'quill/dist/quill.snow.css'
  import { setTimeout } from 'timers'
  // 富文本提示
  import { addQuillTitle } from '@/libs/quill-title.js'
  export default {
    components: {
      quillEditor
    },
    data () {
      return {
        sort:'',
        imageUrl: '',
        content: '',
        form: {
          majorWord: '',
          status: '',
          sort:'',
          seoDesc:'',
          seoKeyword:'',
          remark:'',
          majorWordDetail:'',
          // memo: '',
          // advertVideoUrl: ''
        },
        // typeStr: '',
        actionUrl: '',
        imageList: [], //上传的文件列表(pc)
        phoneImageList: [],//上传的文件列表(web)
        videoList: [],
        editorOption: {
          modules: {
           toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'font': [] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'align': [] }],
              ['clean'],
              ['link', 'image', 'video']
            ]
          }
        },
      }
    },
    activated() {
      this.onReset()
      let sortNum = this.$route.query.sort
      this.form.sort = sortNum
      this.sort = sortNum
      this.form={
        sort:this.sort
      }
      // this.typeStr = this.$route.params.type
      // this.init()
    },
    created() {
      this.actionUrl = this.$api.upload()
    },  
    mounted() {
      // addQuillTitle();
      // this.$refs.myTextEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler);
      // console.log(this.$route)
      let sortNum = this.$route.query.sort
      this.form.sort = sortNum
      this.sort = sortNum
      this.form={
        sort:this.sort
      }
    },
    methods: {
      // init(){
      //   //获取分类
      //   // this.form.type = parseInt(this.typeStr);
      //   //获取排序
      //   this.$api.advert.getSort(this.form.type).then(res => {
      //         if(res.success) {
      //           this.form.sort = res.data
      //         }
      //       })
      // },
      imgHandler(state){
        this.addRange = this.$refs.myTextEditor.quill.getSelection()
        if (state) {
          let fileInput = document.getElementById('uploadHidden')
          fileInput.click(); // 加一个触发事件
        }
      },
      onSubmit() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            let params = this.form
            this.$api.aggregation.add(this.form).then(res => {
              if(res.success) {
                // this.$message.success('保存成功')
                // this.$refs.form.resetFields()
                // this.videoList = [];
                // this.$router.push('/advert/list');
                this.form.sort=this.sort
                this.preview(res.data)
              }
            })
          }
        })
      },
      preview(id){
        console.log(id)
        this.$confirm('是否进行预览？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$router.push('/aggregate/detail/' + id)
        }).catch(() => {
          this.$router.push('/aggregate');
        });
      },
      onReset() {
        this.$refs.form.resetFields()
        this.form.sort=this.sort
        this.content=''
      },
      onEditorChange(editor) {
        this.form.majorWordDetail = this.content
        // console.log('editor blur!', editor)
      },
      imageSuccess(res, file) { //pc图片上传成功的回调
        this.form.pcCoverImage = res.data.totalUrl
        this.$forceUpdate()
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      phoneImageSuccess(res, file) {//web图片上传成功的回调
        this.form.wapCoverImage = res.data.totalUrl
        this.$forceUpdate()
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      quillSuccess(res, file, fileList){
        this.$message.success('上传成功');
        const imgUrl = res.data.totalUrl;
        this.$refs.myTextEditor.quill.insertEmbed(this.addRange != null ? this.addRange.index : 0, 'image', imgUrl)
      },
      // videoSuccess(res, file) {
      //   if(res.success) {
      //     this.form.advertVideoUrl = res.data.totalUrl
      //   } else {
      //     this.videoList = []
      //   }
      // },
      // videoHandleRemove(file, fileList){
      //   this.form.advertVideoUrl = ''
      // }
    }
  }
</script>
<style lang="less">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>